package com.example.test;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.room.Room;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.PermissionUtils2;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.example.room.AppDatabase;
import com.example.room.entity.Order;
import com.example.room.repository.OrderRepository;
import com.example.room.mv.OrderViewModel;
import com.example.room.mv.OrderViewModelFactory;
import com.example.room.R;
import com.example.room.entity.User;
import com.example.room.repository.UserRepository;
import com.example.room.mv.UserViewModel;
import com.example.room.mv.UserViewModelFactory;
import com.example.room.UserWithOrders;

import java.util.List;

public class MainActivity extends BaseActivity {

    private static AppDatabase appDatabase;
    UserViewModel userViewModel;
    OrderViewModel orderViewModel;
    private void initViewModel() {

//                Room.databaseBuilder(App.this, AppDatabase.class, "app-database")
//                .addMigrations(AppDatabase.MIGRATION_1_2)
//                .build();
//        AppDatabase appDatabase = Room.databaseBuilder(App.this, AppDatabase.class, "app-database")
//                .addMigrations(AppDatabase.MIGRATION_1_2)  // 如果有版本升级的话
//                .build();

        boolean isCreate = FileUtils.createOrExistsFile(AppDatabase.dbPath);
        if (isCreate) {
            LogUtils.v("【数据库】创建路径= " + AppDatabase.dbPath);
            appDatabase = Room.databaseBuilder(MainActivity.this, AppDatabase.class, AppDatabase.dbPath).build();

            // 创建 UserRepository 实例（假设 UserRepository 包含了 Room 数据库的 DAO）
            UserRepository userRepository = new UserRepository(appDatabase.userDao());
            // 使用自定义的 ViewModelProvider.Factory
            UserViewModelFactory viewModelFactory = new UserViewModelFactory(userRepository);
            userViewModel = new ViewModelProvider(MainActivity.this, viewModelFactory).get(UserViewModel.class);
            userViewModel.getSearchUsers().observe(MainActivity.this, new Observer<List<User>>() {
                @Override
                public void onChanged(List<User> users) {
                    LogUtils.v("【数据库】搜索用户改变= " + (users != null ? users.size() : 0));
                }
            });


            // 创建 UserRepository 实例（假设 UserRepository 包含了 Room 数据库的 DAO）
            OrderRepository orderRepository = new OrderRepository(appDatabase.orderDao());
            // 使用自定义的 ViewModelProvider.Factory
            OrderViewModelFactory orderFactory = new OrderViewModelFactory(orderRepository);
            orderViewModel = new ViewModelProvider(MainActivity.this, orderFactory).get(OrderViewModel.class);

            LogUtils.v("【数据库】创建成功");
        } else {
            //Toast.show("数据库创建异常");
            LogUtils.e("【数据库】创建失败");
        }

        // 设置监听，在数据变更时，更新View中内容
        //userViewModel.insertUser(user)
//                .observe(
//                        MainActivity.this,
//                        new Observer<Boolean>() {
//                            @Override
//                            public void onChanged(Boolean activated) {
//
//                            }
//                        }
//                );


    }


    /**
     * 请求文件权限。
     */
    private void requestPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//R=30=11

            if (!PermissionUtils2.isExternalStorage()) {
                PermissionUtils2.requestExternalStorage(new PermissionUtils2.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        LogUtils.d("【权限申请】有外部存储权限-11版本");
                    }

                    @Override
                    public void onDenied() {
                        LogUtils.d("【权限申请】(拒绝)外部存储权限-11版本");
                    }
                });

            } else {
                LogUtils.d("【权限申请】有外部存储权限-11版本");
            }

        } else {
            if (!PermissionUtils.isGranted(PermissionConstants.STORAGE)) {
                LogUtils.w("【申请权限-1/6】(没)授权读写");

                PermissionUtils.permissionGroup(PermissionConstants.STORAGE)
                        .explain(new PermissionUtils.OnExplainListener() {//设置权限请求前的解释
                            @Override
                            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                                LogUtils.w("【申请权限-2/6】设置权限请求前的解释");

                            }
                        })
                        .rationale(new PermissionUtils.OnRationaleListener() {//设置拒绝权限后再次请求的回调接口
                            @Override
                            public void rationale(@NonNull UtilsTransActivity activity, @NonNull ShouldRequest shouldRequest) {
                                LogUtils.w("【申请权限-3/6】设置拒绝权限后再次请求的回调接口= " + shouldRequest);

                                shouldRequest.again(true);//是否再次提醒
                            }
                        })
                        .callback(new PermissionUtils.FullCallback() {
                            @Override
                            public void onGranted(@NonNull List<String> granted) {
                                LogUtils.w("【申请权限-4/6】同意 -> 配置文件");
                                for (String s : granted) {
                                    LogUtils.v("【申请权限】获取到的权限= " + s);
                                }
                            }

                            @Override
                            public void onDenied(@NonNull List<String> permissionsDeniedForever, @NonNull List<String> permissionsDenied) {
                                LogUtils.w("【申请权限-5/6】拒绝授权");

                                LogUtils.v("【申请权限】永远拒绝= " + permissionsDeniedForever);
                                LogUtils.v("【申请权限】拒绝= " + permissionsDenied);
                                if (!permissionsDenied.isEmpty()) {
                                    LogUtils.v("【申请权限】拒绝= " + permissionsDenied);
                                }
                                LogUtils.e("【申请权限】"
                                        + "\n拒绝= " + permissionsDenied
                                        + "\n永远拒绝= "+permissionsDeniedForever
                                );

                                if (!permissionsDenied.isEmpty() && !permissionsDeniedForever.isEmpty()) {
                                    LogUtils.v("【申请权限】跳转系统设置页面= " + permissionsDeniedForever.size());
                                }

                            }
                        })
                        .request();
            } else {
                LogUtils.w("【申请权限-6/6】已授权读写");
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv1 = findViewById(R.id.tv1);
        LogUtils.v(tv1);
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });

        TextView tv2 = findViewById(R.id.tv2);
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initViewModel();
            }
        });

        TextView tv3 = findViewById(R.id.tv3);
        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ViewActivity.start(MainActivity.this);
            }
        });

        TextView tv4 = findViewById(R.id.tv4);
        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runOnSubThread(new Runnable() {
                    @Override
                    public void run() {

                        for (int i = 0; i < 10; i++) {
                            User user = new User();
                            user.userId = 100 + i;
                            user.userName = "何洪连" + i;
                            userViewModel.insertUser(user);

                            User user2 = new User();
                            user2.userId = 200 + i;
                            user2.userName = "HeHonglian" + i;
                            userViewModel.insertUser(user2);
                        }



                        if (false) {
//                            userViewModel.insertUser(user);
//
//                            User user2 = new User();
//                            user2.userId = 2;
//                            user2.userName = "B";
//                            userViewModel.insertUser(user2);
//
//                            Order order = new Order();
//                            order.orderId = 11;
//                            order.userId = user.userId;
//                            order.productName = "AA";
//                            orderViewModel.insertOrder(order);
//                            Order order2 = new Order();
//                            order2.orderId = 22;
//                            order2.userId = user2.userId;
//                            order2.productName = "BB";
//                            orderViewModel.insertOrder(order2);
                        }

                    }
                });
            }
        });

        TextView tv5 = findViewById(R.id.tv5);
        tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userViewModel.getUserWithOrders(1).observe(MainActivity.this, new Observer<UserWithOrders>() {
                    @Override
                    public void onChanged(UserWithOrders userWithOrders) {
                        if (userWithOrders != null) {
                            User user = userWithOrders.user;
                            List<Order> orders = userWithOrders.orders;
                            for (int i = 0; i < orders.size(); i++) {
                                Order order = orders.get(i);
                                LogUtils.v("【数据库】表关联= " + order);
                            }

                        }
                    }
                });
            }
        });

        EditText tvZw = findViewById(R.id.tvZw);
        EditText tvPy = findViewById(R.id.tvPy);
        TextView tv6 = findViewById(R.id.tv6);
        tv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String zw = tvZw.getText().toString().trim();
                String py = tvPy.getText().toString().trim();

                if (false) {
                    userViewModel.searchUsers(zw).observe(MainActivity.this, new Observer<List<User>>() {
                        @Override
                        public void onChanged(List<User> users) {
                            for (User u : users) {
                                LogUtils.w("【数据库】模糊查询= " + u);
                            }
                        }
                    });
                } else {
                    User user = new User();
                    user.userId = 100;
                    user.userName = zw;

                    userViewModel.searchUsers(user).observe(MainActivity.this, new Observer<List<User>>() {
                        @Override
                        public void onChanged(List<User> users) {
                            for (User u : users) {
                                LogUtils.w("【数据库】模糊查询= " + u);
                            }
                        }
                    });
                }

            }
        });




    }
    
}
